package com.cn.controller;

import cn.hutool.core.lang.UUID;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/lock")
public class RedisTestLock implements ILock{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static  final String key_prefix = "lock:";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("testOrderId.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public void testLuaUnlock(){
        String id =key_prefix+ Thread.currentThread().getId();
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                //锁的key
                Collections.singletonList(id),
                //线程标识
                key_prefix + Thread.currentThread().getId()
        );
    }

    /**
     * 获取锁的方式
     * @param timoutSec 锁持有的时间
     * @return
     */
    @Override
    public boolean tryLock(long timoutSec) {
        //获取线程标识
        String threadId = key_prefix+Thread.currentThread().getId();
        //获取锁的方式
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(threadId , threadId , timoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        String threadId = key_prefix+Thread.currentThread().getId();
        String id = stringRedisTemplate.opsForValue().get(threadId);
        //判断是否属于自己的锁
        if (threadId.equals(id)) {
            //通过id删除锁的方式
            stringRedisTemplate.delete(key_prefix+threadId);
        }
    }

    @GetMapping("/redisRedisTest")
    public Object redisRedisTest(){
        try{
            if (tryLock(100l)) {
                System.out.println("执行下单操作");
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            testLuaUnlock();
        }
        return "成功";
    }

    @GetMapping("/restRedisson")
    public Object restRedisson() throws InterruptedException {
        RLock anyLock = redissonClient.getLock("anyLock");
        boolean isLock = anyLock.tryLock(1, 10, TimeUnit.SECONDS);
        if (isLock){
            try {
                System.out.println("执行业务");
            }finally {
                anyLock.unlock();
            }
        }
        return "成功";
    }


    /**
     * 保存优惠价信息
     * @param id
     * @return
     */
    @GetMapping("/testOrderId")
    public Object testOrderId(Integer id){
        stringRedisTemplate.opsForValue()
                //存入库存
                .set("seckill:stock:"+id,"50");
        return "成功";
    }

    /**
     * 进行下单
     * @param id
     * @return
     */
    @GetMapping("/testSeckill")
    public Object testSeckill(Integer id){
        Long result = stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.emptyList(),
                id+"",
                1+"",
                2+""
        );
        int r = result.intValue();
        if (r!=0){
            return r>1?"不能重复下的那":"库存不够";
        }
        return "成功";
    }
}
